﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace COFE.Core.Actions
{
    public class TextScriptParser : IScriptParser
    {
        public Tuple<object, string>[] ParseScript(Stream script)
        {
            List<Tuple<object, string>> retVal = new List<Tuple<object, string>>();

            
            using (var sr = new StreamReader(script))
            {
                string scriptLine = sr.ReadLine();
                while (scriptLine != null) 
                {

                    var scriptParams = scriptLine.Split(' ');
                    if (scriptParams.Length != 2)
                        throw new ArgumentException("Unable to parse " + scriptLine);

                    var command = COFEShared.PropertyDictionary.GetProperty(scriptParams[0]);
                    if (command == null)
                        throw new ArgumentException(scriptParams[0] + " not recognized.");
                    var param = scriptParams[1];
                    retVal.Add(new Tuple<object, string>(command, param));
                    scriptLine = sr.ReadLine();
                }
                
            }

            return retVal.ToArray();
        }

        public Stream GenerateScript(Tuple<object, string>[] commands)
        {
            var ms = new MemoryStream();

            StreamWriter sw = new StreamWriter(ms);

            foreach (var c in commands)
            {
                sw.WriteLine(string.Format("{0} {1}", COFEShared.PropertyDictionary.GetPropertyString(c.Item1), c.Item2));
            }

            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
    }
}
